<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 100px;
            height: 100px;
            background: pink;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box"></div>
</body>
<script>
    // 获取元素
    var box = document.getElementById("box")
    // 给box绑定鼠标按下事件
    box.onmousedown = function (e) {
        // 储存鼠标在元素按下的坐标
        var downE = e || window.event
        // 绑定鼠标移动事件
        window.onmousemove = function (e) {
            // 获取移动的光标的坐标
            var e = e || window.event
            var l = e.clientX - downE.offsetX;   //光标在浏览器的坐标 - 光标在元素按下时的坐标
            var t = e.clientY - downE.offsetY;
            // 设置边界
            if (l <= 0) { l = 0 }
            if (t <= 0) { t = 0 }
            if (l >= window.innerWidth - box.offsetWidth) {
                l = window.innerWidth - box.offsetWidth
            }
            if (t >= window.innerHeight - box.offsetHeight) {
                t = window.innerHeight - box.offsetHeight
            }
            // 给box的left和top赋值
            box.style.left = l + "px";
            box.style.top = t + "px";
        }
    }
    // 鼠标抬起清除移动事件
    box.onmouseup = function () {
        window.onmousemove = null
    }
</script>

</html>